/*******************************************************************************
 * Copyright (c) 2001, 2002 Boris Pruessmann and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *    Boris Pruessmann - Initial implementation.
 ******************************************************************************/
package net.sourceforge.perforce.core.internal;

import net.sourceforge.perforce.core.IOpenValidator;
import net.sourceforge.perforce.core.PerforceCorePlugin;
import net.sourceforge.perforce.core.PerforceException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFileModificationValidator;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;

/**
  * @version $Revision: 225 $
  * @author  <a href="mailto:bpruessmann@users.sourceforge.net">Boris Pruessmann</a>
  */
class FileModificationValidator implements IFileModificationValidator
{
	// --------------------------------------------------------------------------- Private Variables
	
	/** Stores the associated team provider. */
	private P4TeamProvider provider;
	
	// ------------------------------------------------------------------------- Public Constructors
	
	/** Constructor for FileModificationValidator. 
	  *
	  * @param theProvider the associated P4TeamProvider instance.
	  */
	public FileModificationValidator(P4TeamProvider theProvider)
	{
		provider = theProvider;
	}
	
	// ------------------------------------------------------------------------------ Public Methods

	/** @see IFileModificationValidator#validateEdit(IFile[], Object) */
	public IStatus validateEdit(IFile[] files, Object context)
	{
		IOpenValidator[] validators = PerforceCorePlugin.getPlugin().getOpenValidators();
		for (int i = 0; i < validators.length; i++)
		{
			IStatus status = validators[i].validateEdit(files, context);
			if (!status.isOK())
			{
				return status;
			}
		}
		
		try
		{

			provider.openForEdit(files, IResource.DEPTH_ZERO, new NullProgressMonitor());
			return new Status(Status.OK, PerforceCorePlugin.ID, 0, "", null);//$NON-NLS-1$
		}
		catch (PerforceException e)
		{
			return e.getStatus();
		}
	}

	/** @see IFileModificationValidator#validateSave(IFile) */
	public IStatus validateSave(IFile file)
	{
		IStatus result = new Status(IStatus.OK, PerforceCorePlugin.ID, IStatus.OK, "", null);
		if (provider.hasRemote(file))
		{
			try 
			{
				if (!provider.isCheckedOut(file))
				{
					provider.openForEdit(
						new IResource[] { file }, 
						IResource.DEPTH_ZERO, 
						new NullProgressMonitor());
				}
			} 
			catch (PerforceException e) 
			{
				result = e.getStatus();
			}
		}
		
		return result;
	}	
}
